package cn.xinfei.xdecision.shutdown;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Slf4j
public class ThreadPoolShutdownHook {

    public static void shutdownHookByActive(ThreadPoolExecutor threadPoolExecutor, String poolName) {

        threadPoolExecutor.shutdown();
        log.info("{}-stop", poolName);
        try {
            log(threadPoolExecutor, poolName);

            if (!threadPoolExecutor.awaitTermination(30, TimeUnit.SECONDS)) {
                log.warn("{} shutdown gracefully within 30 seconds. Proceeding with forceful shutdown", poolName);
            }
            threadPoolExecutor.shutdownNow();

            log.info("{}-shutdownNow ", poolName);
        } catch (InterruptedException e) {
            log.info("{}-被强制终止...................", poolName);
        }
    }

    private static void log(ThreadPoolExecutor threadPoolExecutor, String poolName) {
        log.info("monitorDetail-{}: " +
                        "PoolSize: {}, CorePoolSize: {}, Active: {}, " +
                        "Completed: {}, Task: {}, Queue: {}, LargestPoolSize: {}, " +
                        "MaximumPoolSize: {},  KeepAliveTime: {}, isShutdown: {}, isTerminated: {}",
                poolName, threadPoolExecutor.getPoolSize(), threadPoolExecutor.getCorePoolSize(), threadPoolExecutor.getActiveCount(),
                threadPoolExecutor.getCompletedTaskCount(), threadPoolExecutor.getTaskCount(), threadPoolExecutor.getQueue().size(), threadPoolExecutor.getLargestPoolSize(),
                threadPoolExecutor.getMaximumPoolSize(), threadPoolExecutor.getKeepAliveTime(TimeUnit.MILLISECONDS), threadPoolExecutor.isShutdown(), threadPoolExecutor.isTerminated());
    }

}
